package com.yinhai.uid.controller;

import com.yinhai.uid.UidGenerator;
import com.yinhai.uid.zookeeper.ZookeeperRegistryCenter;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

/**
 * @author taojie
 * @Date: 2018/12/26 16:56
 * @Description:
 */

@Component
@Path("uid")
public class UidResource {

	@Resource
	private UidGenerator uidGenerator;

	@Resource
	private ZookeeperRegistryCenter zookeeperRegistryCenter;

	@Resource
	private HashOperations<String, String, Object> hashOperations;


	@Path("getId")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public long getId() {
		long id = uidGenerator.getUID();
		System.out.println(id);
		return id;
	}

	@Path("getIds/{number}")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public long[] getIds(@PathParam("number") int number) {
		long start = System.currentTimeMillis();
		long[] ids = uidGenerator.getBatchUID(number);
		System.out.println("===================" + (System.currentTimeMillis() - start) + "========================");
//		int i = ids.length;
//		List ls = new ArrayList();
//		for(int j=0;j<ids.length;j++) {
//			if (!ls.contains(ids[j])) {
//				ls.add(ids[j]);
//			}
//		}
//		int k = ls.size();
//		if (ids.length == ls.size()) {
//			System.out.println("===================没有重复========================");
//		} else {
//			System.out.println("===================重复========================");
//		}
		for(int j=0;j<ids.length;j++) {
			hashOperations.put("id",Long.toString(ids[j]),ids[j]);
		}
		return ids;
	}

	@Path("getIdsWithPost")
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes("application/x-www-form-urlencoded")
	public long[] getIdsWithPost(@FormParam("number") int number) {
		long[] ids = uidGenerator.getBatchUID(number);
		System.out.println(ids);
		return ids;
	}

	@Path("opZk/{data}")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public void opZk(@PathParam("data") String data) {
		zookeeperRegistryCenter.persist("/test2",data);
	}

	@Path("getSysTime")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public long getSysTime() {
		return System.currentTimeMillis();
	}

	@Path("keys")
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public long keys() {
		return hashOperations.keys("id").size();
	}
}
